<? 
require("../../common/init.php");
set_time_limit(0);


if(isset($_GET['product_category']) && $_GET['product_category']!='') {
	$product_category_param=$_GET['product_category'];
}else{
	die("no product_category defined!");	
}



$url="http://dara.gindart.com/Dara/dara_website_product_category_sync.php?product_category=".$product_category_param;

$result=json_decode (curl_call($url)); 

$product_category_arr=$result->product_category;
$product_group_arr=$result->product_group;

//add 10000 to product_category to avoid duplicate key between product category and product_group
print_r($product_category_arr);
print_r($product_group_arr);
try {
	$db->begin_transaction();

	//clear all old product_category
	$product_category->exec("delete from product_category");

	
	if(count($product_category_arr) > 1) {
		$i=0;
		foreach($product_category_arr as $row) {
			$i++;
			$row_arr=explode("|",$row);
			$arr=array(
				'seq_no'=>$i,
				'parent_category_id'=>0,
				'name_en'=>$row_arr[1],
				'description_en'=>$row_arr[1],
				'id'=>($row_arr[0]+10000),
			);

			$product_category->insert($arr);
		}
	}
	
	
	
	$i=0;
	foreach($product_group_arr as $row) {
		$i++;
		$row_arr=explode("|",$row);
		$arr=array(
			'seq_no'=>$i,
			'parent_category_id'=>((count($product_category_arr) > 1)?($row_arr[2]+10000):0),
			'name_en'=>$row_arr[1],
			'description_en'=>$row_arr[1],
			'id'=>$row_arr[0],
		);

		$product_category->insert($arr);
	}
	$db->commit();
}
catch(PDOException $ex) {
	print_r($ex);
	$db->rollBack();
	//log
}

function curl_call($url)
{
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_ENCODING, 'UTF-8');
	curl_setopt($ch, CURLOPT_TIMEOUT, 60);
	$output = curl_exec($ch);
	curl_close($ch);
    return $output; 	
}
?>